import { redirect } from "next/navigation";
import { getAuthorizationCodeUrl, getTokenInfo } from "./func";

export interface TokenInfo {
  expires_in: number,
  refresh_token: string,
  access_token: string,
  scope: string,
}

export async function handleWithToken<T>(func: (tokenInfo: TokenInfo) => T): Promise<T | never> {
  const tokenInfo = await getTokenInfo();
  if (tokenInfo) {
    return func(tokenInfo);
  }
  return redirect(getAuthorizationCodeUrl());
}

export async function onlyGetFrom(getUrl: (token: TokenInfo) => string): Promise<any> {
  return handleWithToken(async (token) => {
    const url = getUrl(token);
    const result = await fetch(url);
    const text = await result.text();
    return new Response(text, {
      headers: {
        "Content-Type": result.headers.get("Content-Type") || "text/plain",
      },
    });
  });
}
